<?php
if (!defined('IN_WONDERSHARE')){
	die('Hacking attempt');
}

class TemplateApiModule {

	private $db;
   
	public function __construct(){
		$this->db = $GLOBALS['db'];
	}
	
	//note 取得某类型的所有接口
	public function getList( $sid, $type ){
		
		$where = '';
		if( $sid > 0 ){
			$where = "AND tid IN (SELECT DISTINCT tid FROM tpl_api_detail WHERE sid = 0 or sid = {$sid})";
		}
		
		$sql = "SELECT tid, name FROM tpl_api WHERE `type` = '{$type}' {$where} ORDER BY tid ASC";
		return $this->db->getAll( $sql );
	}
	
	//note 取得某个API信息
	public function getApi( $tid ){
		$sql = "SELECT * FROM tpl_api WHERE `tid` = '{$tid}'";
		return $this->db->getOneRs( $sql );
	}
	
	//note 添加
	public function add( $name, $fun, $type, $desc ){
		$sql = "INSERT INTO tpl_api( `name`, `fun`, `type`, `desc` ) VALUE ('{$name}','{$fun}','{$type}','{$desc}')";
		$this->db->query( $sql );
		return $this->db->insert_id();
	}
	
	//note 添加接口详细
	public function addDetail( $tid, $sid, $detail ){
		$sql = "INSERT INTO tpl_api_detail( `tid`, `sid`, `detail` ) VALUE ('{$tid}','{$sid}','{$detail}')";
		return $this->db->query( $sql );
	}
	
	//note 编辑
	public function change( $tid, $name, $fun, $type, $desc ){
		$sql = "UPDATE tpl_api SET `name` = '{$name}', `fun` = '{$fun}', `type` = '{$type}', `desc` = '{$desc}' WHERE tid = '{$tid}'";
		return $this->db->query( $sql );
	}
	
	//note 删除
	public function del( $tid ){
		$sql = "DELETE FROM tpl_api WHERE tid = '{$tid}'";
		$this->db->query( $sql );
		
		$this->delDetail( $tid );
	}
	
	//ntoe 删除接口详细
	public function delDetail( $tid ){
		$sql = "DELETE FROM tpl_api_detail WHERE tid = '{$tid}'";
		$this->db->query( $sql );
	}
	
	//note 取得接口详细
	public function getDetail( $tid ){
		$sql = "SELECT * FROM tpl_api_detail WHERE tid = '{$tid}' ORDER BY did ASC";
		return $this->db->getAll( $sql );
	}
		
}